package com.longrise.android.byjk.plugins.aboutme.personalInfo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.event.MineRefreshEvent;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.android.byjk.plugins.aboutme.GarbageComponent;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.caculate.BitmapCaculate;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.change.BundlePhoneActivity;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.change.ChangeInfoActivity;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.person_honor.PersonHonorShowActivity;
import com.longrise.android.byjk.plugins.aboutme.personalInfo.product_show.ProductProgramActivity;
import com.longrise.android.byjk.plugins.request.AppBaseRequest;
import com.longrise.android.byjk.plugins.request.AppBaseResult;
import com.longrise.android.byjk.plugins.request.ChangeInforRequest;
import com.longrise.android.byjk.plugins.request.RequestThread;
import com.longrise.android.byjk.plugins.vip.VipDescriptionActivity;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.android.byjk.widget.crop.Crop;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.DZZWTools;
import com.longrise.common.utils.FolderConstants;

import org.greenrobot.eventbus.EventBus;

import java.io.File;


/**
 * Created by callxkj on 2016/11/18.
 * presenter
 */

public class PersonalPresenter implements PersonalInfoContract.Presenter {

    private static final String TAG = "PersonalPresenter";

    private final PersonalInfoContract.View mView;
    public static final int CHANGENICKNAME = 1;
    public static final int CHANGETRUENAME = 2;
    public static final int CHANGEIDNUMBER = 3;
    public static final int CHANGEPHONENUMBER = 4;
    public static final int CHANGEZYXX = 5;
    public static final int CHANGEPROFILE = 6;
    public static final int CHANGECPZS = 7;
    public static final int TOCAMERA = 8;
    public static final int TOGALLERY = 9;
    public static final int PERSONALSHOW = 10;
    public static final int AUTHOR = 11;
    public static final int RUNLOGIN = 12;
    public static final int CHANGEGRRY = 13;
    private File mImageFile;
    private Context mContext;
    private String iconType;

    private Uri mImageUri;

    private final int VIP_STATE3 = 3;

    private boolean mFinished;

    @Override
    public void setFinished() {
        mFinished = true;
    }

    public PersonalPresenter(PersonalInfoContract.View view, Context context) {
        this.mView = view;
        this.mContext = context;
    }

    @Override
    public void init() {
        setData();
    }

    private void setData() {
        if (mView != null) {
            requestZYXX();
//            getMyMeedal();
            UserInfor userInfor = UserInfor.getInstance();
            mView.setHeadIcon(userInfor.getUserHeadIcon(), false);//头像
            mView.setNickName(userInfor.getUserNickName());//昵称
            mView.setUserName(userInfor.getUserName());  //用户名
            mView.setTrueName(userInfor.getPersonname());//真实姓名
            mView.setIDNumber(userInfor.getIsRealCardNo().equals("1") ? userInfor.getUsersfzh() : "");//身份证号
            mView.setPhoneNumber(userInfor.getUserphone());//手机号
//            mView.setZYXX(userInfor.getZYXX());//执业信息
            mView.setProfile(userInfor.getUserProfile());//个人简介
            mView.setCPZS(userInfor.getUserCPZS());//产品展示
            mView.setGRRY(userInfor.getUserGRRY());//个人荣誉
            mView.setWXURL(userInfor.getWechatimgurl());//微信二维码
            mView.showLoading(false);
        }
    }

    /**
     * V1.3.7执业信息需要动态查询
     */
    public void requestZYXX() {
        EntityBean bean = new EntityBean();
        bean.set("cardno", UserInfor.getInstance().getUsersfzh());
        final EntityBean reqBean = new EntityBean();
        reqBean.set("bean", bean);
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl, "bbt_user_sDevCertInfo", reqBean, new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                if (mFinished) {
                    return;
                }
                try {
                    EntityBean resultBean = (EntityBean) result;
                    int resultstate = resultBean.getInt("resultstate");
                    if (resultstate != 1) {
                        mView.showToast(resultBean.getString("resultdesc"));
                        return;
                    }
                    EntityBean resultStr = resultBean.getBean("result");
                    parseZYXX(resultStr);
                } catch (Exception e) {
                    e.printStackTrace();
                    //数据结构异常
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished(String key, String service) {

            }
        });
    }

    private void parseZYXX(EntityBean resultStr) {
        String certfrom = resultStr.getString("certdesc");
        mView.setZYXX(certfrom);//执业信息
    }

    @Override
    public void openPersonalShow() {
//        VipManager.checkVip(mContext, new VipManager.CheckResultListener() {
//            @Override
//            public void onSuccess() {
//                if (UserInfor.getInstance().getViptype() == VIP_STATE3) {
//                    mView.startActivityForR(PERSONALSHOW, PersonalExhibitionActivity.class);
//                    addGoogleEvent("Member-privileges", "EI-show", "展业秀预览");
//                } else {
//                    showDialog();
//                }
//            }
//        });
        mView.startActivityForR(PERSONALSHOW, PersonalExhibitionActivity.class);
    }

    @Override
    public void changeNickName() {
        mView.startActivityForR(CHANGENICKNAME, ChangeInfoActivity.class);
    }

    @Override
    public void changeUserName() {

    }

    @Override
    public void changeTrueName(String from) {
        //考虑积分进入
        mView.startActivityForR(getIntent(from, ChangeInfoActivity.class, CHANGETRUENAME), CHANGETRUENAME);
//        mView.startActivityForR(CHANGETRUENAME, ChangeInfoActivity.class);
    }

    @Override
    public void changeIDNumber(String from) {
        //考虑积分进入
        mView.startActivityForR(getIntent(from, ChangeInfoActivity.class, CHANGEIDNUMBER), CHANGEIDNUMBER);
//        mView.startActivityForR(CHANGEIDNUMBER, ChangeInfoActivity.class);
    }

    @Override
    public void changePhoneNumber() {
        mView.startActivityForR(CHANGEPHONENUMBER, BundlePhoneActivity.class);
    }

    @Override
    public void changeZYXX() {
        mView.startActivityForR(CHANGEZYXX, ChangeInfoActivity.class);
    }

    @Override
    public void changeProfile() {
        mView.startActivityForR(CHANGEPROFILE, ChangeInfoActivity.class);
    }

    @Override
    public void changeCPZS() {
//        mView.startActivityForR(CHANGECPZS, ProductShowActivity.class);
        mView.startActivityForR(CHANGECPZS, ProductProgramActivity.class);
    }

    @Override
    public void changeGRRY() {
        mView.startActivityForR(CHANGEGRRY, PersonHonorShowActivity.class);
    }

    @Override
    public void toCamera(Context context,String iconType) {
        this.mContext = context;
        this.iconType = iconType;
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// "android.media.action.IMAGE_CAPTURE"
            mImageFile = new File(createPicFile(), System.currentTimeMillis() + ".jpg");
//            Uri mOutPutFileUri = Uri.fromFile(mImageFile);
            Uri mOutPutFileUri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mOutPutFileUri = FileProvider.getUriForFile(mContext, FolderConstants.FILE_PROVIDER, mImageFile);
            } else {
                mOutPutFileUri = Uri.fromFile(mImageFile);
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutPutFileUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            mView.startActivityForR(intent, TOCAMERA);
        } else {
        }
    }

    private File createPicFile() {
        File path1 = new File(FolderConstants.BB_CAMERA_DIR);
        if (!path1.exists()) {
            path1.mkdirs();
        }
        return path1;
    }

    @Override
    public void toGallery(Context context,String iconType) {
        this.mContext = context;
        this.iconType = iconType;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        mView.startActivityForR(intent, TOGALLERY);
    }

    private void beginCrop(Uri source) {
        createPicFile();
        File file = new File(FolderConstants.BB_CAMERA_DIR, System.currentTimeMillis() + "cropped.jpg");
        if (file.exists()) {
            file.delete();
        }
        Uri destination = Uri.fromFile(file);
        Crop.of(source, destination).withMaxSize(480, 640).asSquare().start(((PersonalInfoActivity) mContext));
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            mImageUri = Crop.getOutput(result);
            //Bitmap bitmap = BitmapCaculate.decodeBitmapFromLocalPath(mImageUri.getPath(), 480, 640);
            Bitmap bitmap = BitmapFactory.decodeFile(mImageUri.getPath());
            String bitmapBase64 = BitmapCaculate.bitmapToBase64(bitmap);
            uploadUserHeadIcon(bitmapBase64);
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
        } else if (resultCode == Crop.RESULT_ERROR) {
            DZZWTools.showToast(mContext, mContext.getString(R.string.getlocal_uri_icon), Toast.LENGTH_SHORT);
        }
    }

    private Intent getIntent(String from, Class<?> cls, int changeInforType) {
        Intent intent = new Intent(mContext, cls);
        intent.putExtra("type", changeInforType);
//        intent.putExtra(BBWebHelper.FROM_PAGE, from);
        return intent;
    }

    private void uploadUserHeadIcon(String base64) {
        Bundle bundle = new Bundle();
        if(iconType.equals(PersonalInfoActivity.HEADICON)){
            bundle.putString("bytestr", base64);
            commit("bbt_user_uploadServerImg", bundle);
        }else if(iconType.equals(PersonalInfoActivity.WXICON)){
            bundle.putString("bywxstr", base64);
            commitWx("insh_user_uploadWeChatImg", bundle);
        }
    }


    private void commit(String api, Bundle bundle) {
        show();
        ChangeInforRequest changeInforRequest = new ChangeInforRequest(new HeadIconResult1());
        changeInforRequest.setApi(api);
        RequestThread requestThread = new RequestThread(changeInforRequest);
        requestThread.request(mContext, AppBaseRequest.APP_REQUEST_TAG, bundle);
    }

    private class HeadIconResult1 implements AppBaseResult {

        @Override
        public void onSuccess(Object result) {
            //将本地headicon重新设置 返回图片存放的地址重新设置本地headicon
            EntityBean bean = (EntityBean) result;
            if (bean != null && bean.getInt("resultstate") == 1) {
                EntityBean resultBean = bean.getBean("result");
                if (resultBean != null) {
                    String userheadurl = resultBean.getString("userheadurl");
                    UserInfor.getInstance().setUserHeadIcon(userheadurl);
                    resetHeadIcon();
                }
            }
        }

        @Override
        public void onFailed(String errorLog) {
            DZZWTools.showToast(mContext, mContext.getString(R.string.upload_icon_faile), Toast.LENGTH_SHORT);

        }

        @Override
        public void onFinish() {
            dismiss();
        }
    }

    private void commitWx(String api, Bundle bundle){
        show();
        ChangeInforRequest changeInforRequest = new ChangeInforRequest(new WxIconResult1());
        changeInforRequest.setApi(api);
        RequestThread requestThread = new RequestThread(changeInforRequest);
        requestThread.request(mContext, AppBaseRequest.APP_REQUEST_TAG, bundle);
    }

    private class WxIconResult1 implements AppBaseResult {

        @Override
        public void onSuccess(Object result) {
            //将本地headicon重新设置 返回图片存放的地址重新设置本地headicon
            EntityBean bean = (EntityBean) result;
            if (bean != null && bean.getInt("resultstate") == 1) {
                EntityBean resultBean = bean.getBean("result");
                if (resultBean != null) {
                    String wechatimgurl = resultBean.getString("wechatimgurl");
//                    UserInfor.getInstance().setUserHeadIcon(userheadurl);
                    mView.setWXvisible(wechatimgurl);
                }
            }
        }

        @Override
        public void onFailed(String errorLog) {
            DZZWTools.showToast(mContext, mContext.getString(R.string.upload_icon_faile), Toast.LENGTH_SHORT);

        }

        @Override
        public void onFinish() {
            dismiss();
        }
    }

    private void resetHeadIcon() {
        if (mView != null) {
            mView.setHeadUri(mImageUri, true);
            MineRefreshEvent event = new MineRefreshEvent();
            event.setHeadIcon(true);
            EventBus.getDefault().post(event);
        }
    }

    public void show() {
        mView.showLoading(true);
    }

    public void dismiss() {
        mView.showLoading(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        boolean isReset = data != null ? data.getBooleanExtra("key", false) : false;
        switch (requestCode) {
            case TOCAMERA:
                if (mImageFile != null && mImageFile.exists()) {
                    beginCrop(Uri.fromFile(mImageFile));
                }
                break;

            case TOGALLERY:
                if (data != null) {
                    Uri uri = data.getData();
                    beginCrop(uri);
                }
                break;

            case Crop.REQUEST_CROP:
                handleCrop(resultCode, data);
                break;

            case CHANGENICKNAME:  //昵称
                if (mView != null && isReset) {
                    mView.setNickName(UserInfor.getInstance().getUserNickName());
                    MineRefreshEvent event = new MineRefreshEvent();
                    event.setName(true);
                    EventBus.getDefault().post(event);
                }
                break;

            case CHANGETRUENAME: //真实姓名
                if (mView != null && isReset) {
                    mView.setTrueName(UserInfor.getInstance().getPersonname());
                    setAuthor();
                }
                break;

            case CHANGEIDNUMBER: //身份证号
                if (mView != null && isReset) {
                    mView.setIDNumber(UserInfor.getInstance().getUsersfzh());
                    setAuthor();
                }
                break;

            case CHANGEPHONENUMBER: //手机号
                if (mView != null && isReset) {
                    mView.setPhoneNumber(UserInfor.getInstance().getUserphone());
                }
                break;

            case CHANGEZYXX: //执业信息
                if (mView != null && isReset) {
                    mView.setZYXX(UserInfor.getInstance().getZYXX());
                }
                break;

            case CHANGEPROFILE: //个人简介
                if (mView != null && isReset) {
                    mView.setProfile(UserInfor.getInstance().getUserProfile());
                }
                break;

            case CHANGECPZS: //产品展示
                if (mView != null && isReset) {
                    mView.setCPZS(UserInfor.getInstance().getUserCPZS());
                }
                break;
            case CHANGEGRRY:  //个人荣誉
                if (mView != null && isReset) {
                    mView.setGRRY(UserInfor.getInstance().getUserGRRY());
                }
                break;
            default:
                break;
        }
    }

//    @Override
//    public void updateMyMedal() {
//        getMyMeedal();
//    }

    private void setAuthor() {
        UserInfor userInfor = UserInfor.getInstance();
        boolean isAuthor = !TextUtils.isEmpty(userInfor.getPersonname()) && !TextUtils.isEmpty(userInfor.getUsersfzh()) && UserInfor.getInstance().getIsRealCardNo().equals("1");
        if (isAuthor) {
            UserInfor.getInstance().setIsauthorised(isAuthor ? true : false);
            GarbageComponent.callBack(AUTHOR, null);
        }
    }

//    private void getMyMeedal() {
//        mView.setMyMedal(MyMedalRankHelper.getMedalRank());
//    }


    private void showDialog() {
        View dialogView = LayoutInflater.from(mContext).inflate(R.layout.dialogview_vip, null, false);
        TextView mTextCancle = (TextView) dialogView.findViewById(R.id.textcancle_vip);
        TextView mTextConfrim = (TextView) dialogView.findViewById(R.id.textconfirm_vip);
        View.OnClickListener mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.textcancle_vip:  //
                        break;

                    case R.id.textconfirm_vip: //
                        Intent intent = new Intent(mContext, VipDescriptionActivity.class);
                        intent.putExtra(VipDescriptionActivity.MODE, VipDescriptionActivity.HOME_PAGE);
                        mContext.startActivity(intent);
                        break;

                    default:
                        break;
                }
                DialogUtil.getInstance().dismiss();
            }
        };
        mTextCancle.setOnClickListener(mOnClickListener);
        mTextConfrim.setOnClickListener(mOnClickListener);
        DialogUtil.getInstance().creatAlertDialog(mContext, dialogView, 266, 159);
    }


}
